<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/21 0021
 * Time: 下午 3:42
 */
namespace app\api\service;

use app\admin\model\OrderAfterSale;
use app\admin\model\Orderitem;
use app\common\BaseHelper;
use app\common\DictConstant;
use app\lib\exception\ParameterException;
use think\Db;

class Aftersale{
    //订单申请售后
    public function refund($postData){
        Db::startTrans();
        try{

            $res = $this->getRefund_fee($postData['order_id'],$postData['product_id'],2);
            //创建售后订单
            $refund = new OrderAfterSale();
            $out_refund_no = Order::makeOrderNo();
            $refund->id = BaseHelper::getUUID();
            $refund->order_item_id = $res['order_item_id'];
            $refund->order_id = $res['order_id'];
            $refund->product_id = $postData['product_id'];
            $refund->reason = isset($postData['reason'])?$postData['reason']:NULL;
            $refund->reason_des = isset($postData['reason_des'])?$postData['reason_des']:NULL;
            $refund->count = $res['count'];
            $refund->damage_type = isset($res['damage_type'])?$res['damage_type']:1;
            $refund->form_id = isset($res['form_id'])?$res['form_id']:NULL;
            $refund->member_phone = $res['member_phone'];
            $refund->out_refund_no = $out_refund_no;
            $refund->transaction_id = $res['transaction_id'];
            $refund->refund_fee = $res['refundprice'];
            $refund->old_total = $res['old_total'];
            if($postData['imgs']){
                //是否上传了售后凭证
                $refund->imgs = $postData['imgs'];
            }
            $refund->save();
            $res['orderpro']->after_sale_status = 1;
            $res['orderpro']->save();
            Db::commit();
            $data =  [
                'order_id' => $postData['order_id'],
                'product_id' => $refund->product_id,
                'out_refund_no' => $out_refund_no,
                'create_date' => $refund->create_date,
                'refund_fee' => $refund->refund_fee
            ];
            return show(config('status.SUCCESS_STATUS'),'创建售后订单成功',$data);
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.ERROR_STATUS'),$ex->msg,'创建售后订单失败');
        }

    }

    //计算售后金额
    public function getRefund_fee($order_id,$product_id,$type = 1){
        $order = \app\common\model\Order::where('id',$order_id)->field('order_price,member_id,total,link_type,status,freight,discount_price,first_order_reduce,transaction_id')->find();
        $Member = \app\admin\model\Member::where('id',$order->member_id)->field('account_number')->find();
        $linkType = $order->link_type;
        $orders = Orderitem::where('order_id',$order_id)->select();
        $orderpro = Orderitem::where(['order_id'=>$order_id,'product_id'=>$product_id])->find();
        $orderrefund = OrderAfterSale::where(['order_item_id'=>$orderpro->id,'product_id'=>$product_id])->find();
        $orderrefundnum = Orderitem::where('order_id',$order_id)->where('after_sale_status','in',[1,2,3,4])->count();
        $this->checkorder($order,$orderpro,$orderrefund);
        $allprice = $order->order_price/100;
        //运费;
        $otherprice = $order->freight/100;
        //计算退款金额
        if($linkType == 1){
            if($orderpro->is_flashsale != 1 && $orderpro->is_repurchase != 1){
                //普通商品
                $allprice = 0;
                foreach ($orders as $v){
                    if($v['is_flashsale'] !=1 && $v['is_repurchase'] != 1){
                        $allprice += ($v['price'] * $v['count']);
                    }
                }
                $allprice = $allprice/100;
                $price = ($orderpro->price/100)  * $orderpro->count;
            }else{
                if($orderpro->is_flashsale == 1){
                    $price = ($orderpro->flashsale_price/100)  * $orderpro->count;
                }
                if($orderpro->is_repurchase == 1){
                    $price = ($orderpro->repurchase_price/100)  * $orderpro->count;
                }
            }
        }elseif ($linkType == 2){
            $price = ($orderpro->group_price/100)  * $orderpro->count;
        }else{
        }
        $discount = $order->discount_price + $order->first_order_reduce; //订单优惠金额
        if(count($orders) - $orderrefundnum > 1){
            if($discount != 0){
                if($orderpro->is_flashsale == 1 || $orderpro->is_repurchase == 1){
                    $refundprice = $price;
                }else{
                    $refundprice = $price-($discount/100)*$price/$allprice;
                }

            }else{
                $refundprice = $price;
            }
        }else{
            //最后一笔订单要退邮费和包装费
            if($discount != 0){
                if($orderpro->is_flashsale == 1 || $orderpro->is_repurchase == 1){
                    $refundprice = $price + $otherprice;
                }else{
                    $refundprice = $price-($discount/100)*$price/$allprice + $otherprice;
                }

            }else{
                $refundprice = $price + $otherprice;
            }
        }
        $refundprice = (int)(sprintf("%.2f",$refundprice * 100));
        if($refundprice > (int)$order->total){
            throw new ParameterException([
                'msg' => '申请售后的金额不能大于订单总金额'
            ]);
        }
        if($refundprice <= 0){
            $refundprice = 1;
        }
        $data = [
            'member_phone' => $Member->account_number,
            'order_id' => $order_id,
            'order_item_id' => $orderpro->id,
            'count' => $orderpro->count,
            'transaction_id' => $order->transaction_id,
            'old_total' => $order->total,
            'refundprice' => $refundprice,
            'orderpro' => $orderpro,
            'order' => $order
        ];
        if($type == 1){
            return $refundprice;
        }else{
            return $data;
        }
    }

    private function checkorder($order,$orderpro,$orderrefund){
        if(!$order){
            throw new ParameterException([
                'msg' => '该订单不存在'
            ]);
        }
        if(!$orderpro){
            throw new ParameterException([
                'msg' => '该订单商品不存在'
            ]);
        }
//        if($order->status!=2 && $order->status!=8){   //status = 3 已经发货订单 用户与商家协商自行处理
//            throw new ParameterException([
//                'msg' => '该订单不能售后'
//            ]);
//        }
        if($orderrefund){
            throw new ParameterException([
                'msg' => '一个订单只能进行一次售后'
            ]);
        }
        if(!in_array($orderpro->old_status,[2,4,6,7])){
            throw new ParameterException([
                'msg' => '此商品不能进行售后了'
            ]);
        }
    }
}